package com.walala.logic.server;

import java.net.InetSocketAddress;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.walala.logic.cache.ServerCache;
import com.walala.logic.common.Constant;
import com.walala.logic.handler.MsgHandler;
import com.walala.logic.protocol.ProtocolPackage;
import com.walala.logic.service.SendDataService;
import com.walala.logic.utils.IPUtils;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * 消息处理器统一入口
 * @author KayLi
 *
 */
public class ServerHandler extends ChannelInboundHandlerAdapter {

	private Logger logger = LoggerFactory.getLogger(ServerHandler.class);
	
	@Override
	public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
		logger.info("[channelRead] channel id=[{}]", ctx.channel().id());
		Channel channel = ctx.channel();
		InetSocketAddress address = (InetSocketAddress) channel.remoteAddress();
		String clientIp = address.getHostString();
		int port = address.getPort();
		String clientKey = IPUtils.ipToLong(clientIp) + ":" + port;
		ProtocolPackage pack = (ProtocolPackage) msg;
		short command = pack.getCommand();
		logger.info("[cahnnel read] cmd:[{}],remoteIp:[{}],clientKey:[{}]",command,clientIp,clientKey);
		MsgHandler handler = ServerCache.getHandler(command);
		if(null != handler) {
			handler.process(pack);
		}else {
			logger.error("[channel read] handler is null,cmd:[{}],remoteIp:[{}],clientKey:[{}]",command,clientIp,clientKey);
			pack.setResult(Constant.Result_Code.paramError.value);
			pack.setProtoBody(null);
			//将错误信息发送到客户端
			//SendDataService.sendData(clientKey,pack);
		}
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		logger.info("[channelActive] channel id=[{}]", ctx.channel().id());
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		logger.info("[channelInactive] channel id=[{}]", ctx.channel().id());
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		logger.info("[exceptionCaught]:", cause);
	}

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		logger.info("[userEventTriggered] channel id=[{}]", ctx.channel().id());
	}
	
}
